package com.javasm.service;

import com.javasm.entity.LoginUser;
import com.javasm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class LoginPhoneService implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 根据手机号查询用户对象
     * @param phone 前端传的手机号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        // 从数据库查询用户
        User user = userService.getByPhone(phone);
        if(user == null){
            return null;
        }

        // 把用户信息封装到一个 userdetails 对象中，UserDetails是一个接口，LoginUser实现了这个接口
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        setRoles(loginUser);
        return loginUser;
    }
    /**
     * TODO 本来角色应该从数据库中查出来，但是我偷个懒
     * @param loginUser
     */
    private void setRoles(LoginUser loginUser) {
        List<String> roles = new ArrayList<>();
        if("admin".equals(loginUser.getUsername())){
            roles.add("admin");
        }
        if("fengxiansheng".equals(loginUser.getUsername())){
            roles.add("user");
        }
        loginUser.setRoles(roles);
    }
}